#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include <cstdio>
#include <cerrno>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
const std::string MyFifoPath="./myfifo";
#define Creater 1
#define User 2
#define BaseSize 4096

class Fifo
{
private:
bool OpenFifo(const int mode)
{
    _fd =open(_path.c_str(),mode);
    if(_fd<0) return false;
    return true;
}


public:
Fifo(const std::string& path,const int& who)
:_path(path),_who(who)
{
    if(who==Creater)
    {
        int res =mkfifo(_path.c_str(),0666);
        if(res!=0)
        perror("Fifo");
        std::cout<<"Creat fifo sucess!"<<std::endl;
    }
}
~Fifo()
{
    if(_who==Creater)
    {
        int res = unlink(_path.c_str());
        if(res<0)
        perror("unlink");
        std::cout<<"Fifo释放成功"<<std::endl;
    }
    if(_fd!=-1)
    close(_fd);
}
bool OpenForWrite()
{
    std::cout<<"写端正在打开文件"<<std::endl;
    return OpenFifo(O_WRONLY);
}
bool OpenForRead()
{
    std::cout<<"读端正在打开文件"<<std::endl;
    return OpenFifo(O_RDONLY);
}
int ReadFifo(std::string *out)
{
    char buffer[BaseSize]={0};
    int n =read(_fd,buffer,BaseSize);
    if(n>0)
    {
        std::cout<<"Read在发力！"<<std::endl;
        if(n!=BaseSize)
        buffer[n]=0;
        *out = buffer;
    }
    return n;
}
int WriteFifo(const std::string& in)
{
    std::cout<<"Write在发力"<<std::endl;
    return write(_fd,in.c_str(),in.size());
}




private:
int _fd=-1;//防止操作失误
std::string _path;
int _who;
};